package java8.stream.utility;

import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class Utils {

    public static <E> Iterable<E> iterableOf(Stream<E> stream) {
        return stream::iterator;
    }


    // Adapter from Iterable<E> to Stream<E>
    public static <E> Stream<E> streamOf(Iterable<E> iterable) {
        return StreamSupport.stream(iterable.spliterator(), false);
    }


    public static long pi(long n) {
        return LongStream.rangeClosed(2, n)
                .mapToObj(BigInteger::valueOf)
                .filter(i -> i.isProbablePrime(50))
                .count();
    }

    // Prime-counting stream pipeline - parallel version
    public static long piParallel(long n) {
        return LongStream.rangeClosed(2, n)
                .parallel()
                .mapToObj(BigInteger::valueOf)
                .filter(i -> i.isProbablePrime(50))
                .count();
    }


    public static void main(String[] args) {
        //记录开始时间和结束时间
        Instant start = Instant.now();
        //System.out.println(pi((long) Math.pow(10d, 8d)));
        //System.out.println("串行耗时："+Duration.between(start, Instant.now()).toMillis());
        System.out.println(piParallel((long) Math.pow(10d, 8d)));
        System.out.println("并行耗时："+Duration.between(start, Instant.now()).toMillis());
    }

}
